package com.chance.cc.crawler.prod.command.job.domain.news.xhs.notes;

import com.alibaba.fastjson.JSON;
import com.chance.cc.crawler.core.CrawlerEnum;
import com.chance.cc.crawler.core.CrawlerJob;
import com.chance.cc.crawler.core.downloader.HttpConfig;
import com.chance.cc.crawler.core.downloader.HttpConstant;
import com.chance.cc.crawler.core.downloader.HttpPage;
import com.chance.cc.crawler.core.downloader.HttpRequestBody;
import com.chance.cc.crawler.core.filter.FilterUtils;
import com.chance.cc.crawler.core.queue.crawler.CrawlerQueueConfig;
import com.chance.cc.crawler.core.record.CrawlerRecord;
import com.chance.cc.crawler.core.record.CrawlerRequestRecord;
import com.chance.cc.crawler.meta.core.bean.CrawlerMetaConstant;
import com.chance.cc.crawler.meta.core.bean.job.CrawlerScheduleJob;
import org.apache.commons.lang3.StringUtils;

import static com.chance.cc.crawler.core.CrawlerEnum.CrawlerRequestType.*;

/**
 * @author lt
 * @version 1.0
 * @date 2021-06-17 10:48:32
 * @email okprog@sina.com
 */
public class XhsInitCrawlerSchedulerJob extends XhsCommonCrawlerSchedulerJob {
    private static final String site = "user_notes";
    private static final String siteBiz = "notes";

    private static final String startUrl  = "https://www.xiaohongshu.com/fe_api/burdock/weixin/v2/user/";

    private static final String crawler_level = "trace";
    private static final String requestQueueName = StringUtils.joinWith("-","crawler",domain, site, crawler_level,"queue");
    private static final String resultQueueName = StringUtils.joinWith("-","crawler",domain, site, crawler_level,"update","queue");


    public static void main(String[] args) {
        publishCrawlerScheduleJobInfo();
    }

    /**
     * 发布任务信息
     * @return
     */
    public static CrawlerJob publishCrawlerScheduleJobInfo(){

        CrawlerJob crawlerJob = crawlerScheduler();

        //发布定时任务
        CrawlerScheduleJob crawlerScheduleJob = new CrawlerScheduleJob();
        crawlerScheduleJob.setDomain(domain);
        crawlerScheduleJob.setCrawlerJob(JSON.toJSONString(crawlerJob));
        crawlerScheduleJob.setJobType(CrawlerMetaConstant.ScheduleCrawlerJobType.crawler.enumVal());
        crawlerScheduleJob.setNote("小红书账户采集追溯采集任务");
        crawlerScheduleJob.setCrawlerKey(crawlerJob.generateCrawlerKey());
        HttpPage httpPage = metaServiceCommand.addOrUpdateCrawlerScheduleJob(crawlerScheduleJob);
        System.out.println("发布任务：" + httpPage.getRawText());
        return crawlerJob;
    }

    public static CrawlerJob crawlerScheduler(){

        //文章采集
        CrawlerRequestRecord articleCrawler = doSearchNewsCrawler();
        CrawlerRequestRecord crawlerInitRequestRecord = initCommentRecord(articleCrawler);

        //配置结果队列信息
        CrawlerQueueConfig crawlerQueueConfig = new CrawlerQueueConfig(
                resultQueueName,
                CrawlerQueueConfig.Content.result,
                CrawlerQueueConfig.Storage.redis,
                CrawlerQueueConfig.Structure.list);

        //同步到mysql callback record
        CrawlerRequestRecord syncUpdateCrawlerRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domain + "_" + site +"_sync", turnPageItem)
                .httpUrl(metaServiceHttpPrefix + "/crawler/domain/common/api/v1/"+domain+"/search/results/sync?resultQueue="
                        +resultQueueName + "&site=" + site)
                .requestLabelTag(supportCallback)
                .requestLabelTag(internalDownload)
                .build();

        CrawlerJob crawlerJob = CrawlerJob.builder()
                .triggerInfo(domain,
                        CrawlerMetaConstant.ScheduleJobTrigger_Cron,
                        System.currentTimeMillis(),
                        StringUtils.joinWith("-", domain, site, crawler_level, CrawlerMetaConstant.ScheduleJobTriggerJob_Realtime))
                .crawlerRequestQueue(CrawlerMetaConstant.redisRequestQueue(requestQueueName))
                .kafkaResultPipeline("article_result", kafkaTopic, null)
                .fileResultPipeline("file","/data/chance_crawler_runner/logs/node/xhs-data/user-notes-trace.log",false)
                .queueResultPipeline("article_updated",crawlerQueueConfig)
                .crawlerJobThreadNumber(20)
                .requestRecord(articleCrawler)
                .supportRecord(getAuthRecord(site))
                .supportRecord(crawlerInitRequestRecord)
                .supportRecord(syncUpdateCrawlerRecord)
                .build();

        crawlerJob.getScheduleTags().getCategoryTag().addLabelTag(CrawlerEnum.CrawlerDataType.comment.enumVal());
        return crawlerJob;
    }

    public static CrawlerRequestRecord initCommentRecord(CrawlerRequestRecord startRequestRecord){
        CrawlerRequestRecord initRecord = CrawlerRequestRecord.builder()
                .itemPageRequest(startRequestRecord)
                .httpUrl(startUrl)
                .recordKey(startUrl)
                .releaseTime(System.currentTimeMillis())
                .needWashed(false)
                .needParsed(false)
                .copyBizTags()
                .build();
        //添加评论去重信息
        CrawlerRecord filterCrawlerRecord = new CrawlerRecord();
        filterCrawlerRecord.setFilter(CrawlerEnum.CrawlerRecordFilter.dateRange);
        filterCrawlerRecord.addFilterInfo(FilterUtils.redisFilterKeyInfo(StringUtils.joinWith("-",filter,domain,site,crawler_level,"comment")));
        filterCrawlerRecord.addFilterInfo(FilterUtils.dateRangeFilterInfo(24,null));
        initRecord.tagsCreator().bizTags().addCustomKV("comment_record_filter_info", JSON.toJSONString(filterCrawlerRecord));
        initRecord.tagsCreator().scheduleTags().getCategoryTag().addLabelTag(CrawlerEnum.CrawlerDataType.comment.enumVal());
        initRecord.tagsCreator().bizTags().addCustomKV("compare_last_comments",true);

        CrawlerRequestRecord initCommentCrawlerRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domain + "_" + site + "_comment",turnPageItem)
                .httpUrl(metaServiceHttpPrefix + "/crawler/domain/common/api/v1/"+domain+"/results/queue/init?requestQueueName="
                        + requestQueueName + "&site=" + site + "&hourFromNow=170")
                .requestLabelTag(supportSource)
                .requestLabelTag(internalDownload)
                .build();
        HttpRequestBody jsonBody = HttpRequestBody.json(JSON.toJSONString(initRecord), "utf-8");
        initCommentCrawlerRecord.getHttpRequest().setMethod(HttpConstant.Method.POST);
        initCommentCrawlerRecord.getHttpRequest().setRequestBody(jsonBody);
        return initCommentCrawlerRecord;
    }

    /**
     * 初始record
     * @return
     */
    public static CrawlerRequestRecord doSearchNewsCrawler(){

        CrawlerRequestRecord requestRecord = CrawlerRequestRecord.builder()
                .startPageRequest(domain, CrawlerEnum.CrawlerRequestType.turnPage)
                .domain(domain)
                .recordKey(startUrl)
                .httpUrl(startUrl)
                .releaseTime(System.currentTimeMillis())
                .httpConfig(HttpConfig.me(domain))
                .filter(CrawlerEnum.CrawlerRecordFilter.dateRange)
                .addFilterInfo(FilterUtils.redisFilterKeyInfo(StringUtils.joinWith("-","filter",domain,site,"queue")))
                .addFilterInfo(FilterUtils.dateRangeFilterInfo(24*7,null))
                .proxy(proxy)
                .needParsed(false)
                .needWashed(false)
                .build();
        requestRecord.setDownload(false);
        requestRecord.setSkipPipeline(true);
        requestRecord.tagsCreator().bizTags().addDomain(domain);
        requestRecord.tagsCreator().bizTags().addSite(site);
        requestRecord.tagsCreator().bizTags().addSiteBiz(siteBiz);
        return requestRecord;
    }
}
